package com.winit.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * http请求工具类
 * Created by wangjian on 16/10/9.
 */
public class HttpClientUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    /**
     * 发送http get 请求  返回字符串
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String doGet(String url) throws Exception {
        return doGet(url, null);
    }

    public static String doGet(String url, Integer timeOut) throws Exception {

        String rtnStr = "";

        if (StringUtils.isEmpty(url)) {
            logger.error("com.winit.common.util.HttpClientUtil.doGet url为空");
            throw new Exception("发送http get请求,url为空.");
        }

        CloseableHttpClient httpClient = null;
        HttpGet httpGet = null;
        CloseableHttpResponse response = null;

        try {
            httpClient = HttpClients.createDefault();
            httpGet = new HttpGet(url);
            if (null != timeOut) {
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeOut)
                        .setConnectionRequestTimeout(timeOut).setSocketTimeout(timeOut).build();
                httpGet.setConfig(requestConfig);
            }
            response = httpClient.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                rtnStr = EntityUtils.toString(httpEntity);
            }
        } catch (Exception e) {
            logger.error("com.winit.common.util.HttpClientUtil.doGet 发送http get请求异常", e);
            throw new Exception("发送http get请求异常," + e.getMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpGet != null) {
                    httpGet.releaseConnection();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                logger.warn("com.winit.common.util.HttpClientUtil.doGet 发送http get请求,关闭连接异常。", e);
            }
        }
        logger.info("com.winit.common.util.HttpClientUtil.doGet url=" + url + ",返回:" + rtnStr);
        return rtnStr;
    }

    /**
     * 发送http get 请求  返回json
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static JSONObject doGetForJson(String url) throws Exception {
        String str = doGet(url);
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        return JSONObject.parseObject(str);
    }


    public static String doPost(String url, String json) throws Exception {

        String rtnStr = "";

        if (StringUtils.isEmpty(url)) {
            logger.error("com.winit.common.util.HttpClientUtil.doPost url为空");
            throw new Exception("发送http post请求,url为空.");
        }

        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;

        try {
            httpClient = HttpClients.createDefault();
            httpPost = new HttpPost(url);

            StringEntity requestEntity = new StringEntity(json, "utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);

            response = httpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                rtnStr = EntityUtils.toString(httpEntity);
            }
        } catch (Exception e) {
            logger.error("com.winit.common.util.HttpClientUtil.doPost 发送http post请求异常", e);
            throw new Exception("发送http post请求异常," + e.getMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpPost != null) {
                    httpPost.releaseConnection();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                logger.warn("com.winit.common.util.HttpClientUtil.doPost 发送http psot请求,关闭连接异常。", e);
            }
        }
        logger.info("com.winit.common.util.HttpClientUtil.doPost url=" + url + ",返回:" + rtnStr);
        return rtnStr;
    }

    public static JSONObject doPostForJson(String url, String json) throws Exception {
        String str = doPost(url, json);
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        return JSONObject.parseObject(str);
    }
}
